package com.jydd.liaomingframe.app;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;

import com.lm.liaoming.base.BaseApplication;
import com.lm.liaoming.tool.Utils;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.List;

import androidx.multidex.MultiDex;

/**
 * created by 韦敏敏
 * on 2019/11/15
 */
public class SpecialApplication extends BaseApplication {
    private static SpecialApplication instance;
    // 全局Handler对象
    private Handler mainHandler;
    @Override
    protected void init() {
        instance = this;
        initBugly();

        mainHandler = new Handler(getMainLooper());
        String name = getProcessName(getApplicationContext());
        if("com.jydd.liaomingframe".equals(name)){
            /**
             * 若app是多进程应用，因此每个进程被os创建时，
             * onCreate()方法均会被执行一次，
             * 进行辨别初始化，针对特定进程进行相应初始化工作，
             * 此方法可以提高一半启动时间。
             */


        }

    }
    private void initBugly() {
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = Utils.getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // BUGLY初始化
        CrashReport.initCrashReport(getApplicationContext(), "001188041b", true, strategy);
    }

    public static SpecialApplication getInstance(){
        return instance;
    }
    public void post(Runnable runnable){
        mainHandler.post(runnable);
    }
    public void post(Runnable runnable , long delayMillis){
        mainHandler.postDelayed(runnable, delayMillis);
    }
    private String getProcessName(Context context){
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfos = am.getRunningAppProcesses();
        if(runningAppProcessInfos != null && !runningAppProcessInfos.isEmpty()){
            for(ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcessInfos){
                if(runningAppProcessInfo != null){
                    if(runningAppProcessInfo.pid == android.os.Process.myPid() && !TextUtils.isEmpty(runningAppProcessInfo.processName)){
                        return runningAppProcessInfo.processName;
                    }
                }
            }
        }
        return "";
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

}
